package com.JUC.cha05.setc01;

import java.util.concurrent.atomic.AtomicBoolean;

public class InterruptDemo {

    static volatile boolean isStop = false;
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public static void main(String[] args) throws InterruptedException {

        Thread t1= new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\t isInterrupted被更改为true，执行结束");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "\t 正在执行");
            }
        }, "t1");
        t1.start();

        Thread.sleep(20);

        // t2向t1发出协商，将t1的中断标志位设为true希望t1停下来
        new Thread(() -> {
            t1.interrupt();
        }, "t2").start();
        // t1自己设置
//        t1.interrupt();


    }

    private static void m2_AtomicBoolean() throws InterruptedException {
        new Thread(() -> {
            while (true) {
                if (atomicBoolean.get()) {
                    System.out.println(Thread.currentThread().getName() + "\t atomicBoolean.get()被更改为true，执行结束");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "\t 正在执行");
            }
        }, "t1").start();

        Thread.sleep(1);

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 正在执行");
            atomicBoolean.set(true);
        }, "t2").start();
    }

    private static void m1_volatile() throws InterruptedException {
        new Thread(() -> {
            while (true) {
                if (isStop) {
                    System.out.println(Thread.currentThread().getName() + "\t isStop被更改为true，执行结束");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "\t 正在执行");
            }
        }, "t1").start();

        Thread.sleep(1);

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 正在执行");
            isStop = true;
        }, "t2").start();
    }
}
